<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="结算编码" prop="settlementCode">
        <el-input
          v-model="queryParams.settlementCode"
          placeholder="请输入结算编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结算方式" prop="settlementMethod">
        <el-select v-model="queryParams.settlementMethod" placeholder="请选择结算方式" clearable>
          <el-option
            v-for="dict in settlement_ways"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table 
      v-loading="loading" 
      :data="recordList" 
      style="margin-top: 15px; height: 80%"
    >
      <el-table-column label="结算编码" align="center" prop="settlementCode" />
      <el-table-column label="结算金额" align="center" prop="settlementAmount">
        <template #default="scope">
          {{ formatCurrency(scope.row.settlementAmount) }}
        </template>
      </el-table-column>
      <el-table-column label="结算方式" align="center" prop="settlementMethod">
        <template #default="scope">
          <dict-tag :options="settlement_ways" :value="scope.row.settlementMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="startDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结算状态" align="center" prop="settlementStatus">
        <template #default="scope">
          <el-tag :type="statusTagType(scope.row.settlementStatus)">
            {{ scope.row.settlementStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250">
        <template #default="scope">
          <!-- 详情按钮 -->
          <el-button 
            link 
            type="primary" 
            icon="View" 
            @click="handleDetail(scope.row)"
          >详情</el-button>

          <!-- 确认按钮（仅当状态为“待确认”时显示） -->
          <el-button 
            v-if="scope.row.settlementStatus === '待确认'"
            link 
            type="success" 
            icon="Check" 
            @click="handleConfirm(scope.row)"
          >确认</el-button>

          <!-- 驳回按钮（仅当状态为“待确认”时显示） -->
          <el-button 
            v-if="scope.row.settlementStatus === '待确认'"
            link 
            type="danger" 
            icon="Close" 
            @click="handleReject(scope.row)"
          >驳回</el-button>

          <!-- 支付按钮（仅当状态为“待支付”时显示） -->
          <el-button 
            v-if="scope.row.settlementStatus === '待支付'"
            link 
            type="warning" 
            icon="Money" 
            @click="handlePay(scope.row)"
          >支付</el-button>

          <!-- 上传发票按钮（仅当状态为“待支付”时显示） -->
          <el-button 
            v-if="scope.row.settlementStatus === '待支付'"
            link 
            type="info" 
            icon="Upload" 
            @click="handleUploadInvoice(scope.row)"
          >上传发票</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination 
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详情对话框 -->
    <el-dialog :title="detailTitle" v-model="detailOpen" width="800px" append-to-body>
      <el-form :model="detailForm" label-width="120px" disabled>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结算编码">
              <el-input v-model="detailForm.settlementCode" />
            </el-form-item>
            <el-form-item label="合作方编码">
              <el-input v-model="detailForm.partnerCode" />
            </el-form-item>
            <el-form-item label="结算总金额">
              <el-input :value="formatCurrency(detailForm.settlementAmount)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="货币单位">
              <el-input v-model="detailForm.currencyUnit" />
            </el-form-item> -->
            <el-form-item label="协议编码">
              <el-input v-model="detailForm.agreementCode" />
            </el-form-item>
            <el-form-item label="结算方式">
              <dict-tag :options="settlement_ways" :value="detailForm.settlementMethod"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="创建日期">
          <el-input :value="parseTime(detailForm.startDate, '{y}-{m}-{d} {h}:{i}:{s}')" />
        </el-form-item>
        <el-form-item label="实际支付日期">
          <el-input :value="parseTime(detailForm.paymentDate, '{y}-{m}-{d}')" />
        </el-form-item>
        <el-form-item label="结算状态">
          <el-tag :type="statusTagType(detailForm.settlementStatus)">
            {{ detailForm.settlementStatus }}
          </el-tag>
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input v-model="detailForm.remark" type="textarea" />
        </el-form-item>

        <!-- 结算明细表格 -->
        <el-divider content-position="center">结算明细</el-divider>
        <el-table 
          :data="detailSettlementDetailList" 
          border 
          style="width: 100%; margin-top: 10px;"
        >
          <el-table-column label="序号" align="center" prop="index" width="80" />
          <el-table-column label="订单编码" align="center" prop="orderCode" />
          <el-table-column label="订单金额" align="center" prop="orderAmount">
            <template #default="scope">
              <span>{{ scope.row.orderAmount?.toFixed(2) || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结算单编码" align="center" prop="settlementCode" />
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { getPartnerCodeByUserName } from '@/api/settled/partner'
import { parseTime } from "@/utils/ruoyi.js"
import { listRecord, getRecordByPartnerCode, updateRecordStatus,confirmSettlement,rejectSettlement } from "@/api/settled/record.js"
import { getRecord } from "@/api/settled/record"

const { proxy } = getCurrentInstance()
const { settlement_ways } = proxy.useDict('settlement_ways')

// 数据绑定
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const recordList = ref([])
const detailOpen = ref(false)
const detailForm = ref({})
const detailTitle = ref('')
const username = ref('')
const partnerCode = ref('')
const detailSettlementDetailList = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  settlementCode: null,
  settlementMethod: null,
  partnerCode: null
})

// 初始化
async function initial() {
  username.value = useUserStore().userInfo?.name || useUserStore().name
  if (username.value) {
    try {
      const response = await getPartnerCodeByUserName(username.value)
      if (response.code === 200) {
        partnerCode.value = response.msg
        queryParams.partnerCode = partnerCode.value
        getList()
      } else {
        proxy.$modal.msgError(response.msg || "获取合作方编码失败")
      }
    } catch (error) {
      console.error("获取合作方编码失败:", error)
      proxy.$modal.msgError("获取合作方编码失败")
    }
  }
}

// 获取列表数据
async function getList() {
  loading.value = true
  try {
    const response = await getRecordByPartnerCode(queryParams.partnerCode, queryParams.pageNum, queryParams.pageSize)
    console.log('API响应:', response)

    

    if (response.code === 200) {
      if (response.data?.rows) {
        recordList.value = response.data.rows
        total.value = response.data.total
      } else if (Array.isArray(response.data)) {
        recordList.value = response.data
        total.value = response.data.length
      } else {
        recordList.value = response.data ? [response.data] : []
        total.value = response.data ? 1 : 0
      }

      // 添加排序和类型处理
      recordList.value = recordList.value
        .map(row => ({
          ...row,
          partnerType: getPartnerType(row.partnerCode),
          startDate: new Date(row.startDate).toISOString()
        }))
        .sort((a, b) => new Date(b.startDate) - new Date(a.startDate))

      console.log('处理后的记录列表:', recordList.value)
    } else {
      proxy.$modal.msgError(response.msg || "请求失败")
    }
  } catch (error) {
    console.error('请求失败详情:', error)
    proxy.$modal.msgError("数据获取失败：" + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 格式化金额
function formatCurrency(value) {
  return `¥ ${parseFloat(value).toFixed(2)}`
}

// 状态标签样式
function statusTagType(status) {
  const map = {
    '已完成': 'success',
    '待确认': 'warning',
    '已取消': 'danger'
  }
  return map[status] || 'info'
}

// 获取合作方类型
function getPartnerType(partnerCode) {
  if (partnerCode.startsWith('DEALER')) {
    return '经销商'
  } else if (partnerCode.startsWith('LEADER')) {
    return '团长'
  } else if (partnerCode.startsWith('BLOGGER')) {
    return '博主'
  } else if (partnerCode.startsWith('LOGISITICS')) {
    return '物流商'
  } else if (partnerCode.startsWith('SUPPLY')) {
    return '供货商'
  } else if (partnerCode.startsWith('S')) {
    return '供货商'
  } else if (partnerCode.startsWith('1')) {
    return '经销商'
  } else if (partnerCode.startsWith('2')) {
    return '经销商'
  } else if (partnerCode.startsWith('3')) {
    return '经销商'
  } else if (partnerCode.startsWith('4')) {
    return '经销商'
  } else {
    return '未知类型'
  }
}

// 查看详情
function handleDetail(row) {
  getRecord(row.settlementCode).then(response => {
    detailForm.value = response.data
    detailSettlementDetailList.value = response.data.settlementDetailList?.map((item, index) => ({
      ...item,
      index: index + 1
    })) || []
    detailTitle.value = `结算记录详情 - ${row.settlementCode}`
    detailOpen.value = true
  })
}

// 确认操作
async function handleConfirm(row) {
  try {
    const response = await confirmSettlement(row.settlementCode);
    if (response.code === 200) {
      proxy.$modal.msgSuccess("确认成功");
      getList();
    } else {
      proxy.$modal.msgError(response.msg || "确认失败");
    }
  } catch (error) {
    console.error("确认失败:", error);
    proxy.$modal.msgError("确认失败");
  }
}

// 驳回操作
async function handleReject(row) {
  // 弹出一个对话框让用户输入驳回原因
  proxy.$prompt('请输入驳回原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '驳回原因不能为空'
  }).then(({ value }) => {
    return rejectSettlement(row.settlementCode, value);
  }).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("驳回成功");
      getList();
    } else {
      proxy.$modal.msgError(response.msg || "驳回失败");
    }
  }).catch(() => {
    proxy.$message({
      type: 'info',
      message: '取消输入'
    });       
  });
}

// 支付操作
async function handlePay(row) {
  try {
    const response = await payRecord(row.settlementCode)
    if (response.code === 200) {
      proxy.$modal.msgSuccess("支付成功")
      getList()
    } else {
      proxy.$modal.msgError(response.msg || "支付失败")
    }
  } catch (error) {
    console.error("支付失败:", error)
    proxy.$modal.msgError("支付失败")
  }
}

// 上传发票操作
async function handleUploadInvoice(row) {
  try {
    const response = await uploadInvoice(row.settlementCode)
    if (response.code === 200) {
      proxy.$modal.msgSuccess("上传发票成功")
      getList()
    } else {
      proxy.$modal.msgError(response.msg || "上传发票失败")
    }
  } catch (error) {
    console.error("上传发票失败:", error)
    proxy.$modal.msgError("上传发票失败")
  }
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 初始化
onMounted(() => {
  initial()
})
</script>

<style scoped>
.el-table :deep(.cell) {
  white-space: nowrap;
}
</style>